<template>
    <div class="upload-image-container">
        <div class="row no-gutters upload-item-container">
            <div class="col">
                <Progress v-if="percentShow" :percent="percent" status="active"></Progress>
                <!-- quill-editor -->
                <tiny-mce ref="editor"
                          :id="editorID"
                          v-model="content"
                          :toolbar1 = "toolbar"
                          :other_options="options"
                          @editorChange="onChange"
                >
                    <!--@blur="onEditorBlur($event)"-->
                    <!--@focus="onEditorFocus($event)"-->
                    <!--@ready="onEditorReady($event)">-->
                </tiny-mce>

                <Upload v-show="false"
                           accept=".jpg,.jpeg,.png"
                           :on-progress="handleProgress"
                           :action="uploadAction"
                           :data="uploadFormParams"
                           :before-upload="onBeforeUpload"
                           :on-format-error="handleFormatError"
                           :on-success="onImgSuccess"
                           :on-error="onError"
                           :show-file-list="false">
                    <Button ref="uploadButton" size="small" type="primary">点击上传</Button>
                </Upload>
                <Upload v-show="false"
                        accept=".mp4,.wav,.avi"
                        :on-progress="handleProgress"
                        :action="uploadAction"
                        :data="uploadFormParams"
                        :before-upload="onBeforeUpload"
                        :on-format-error="handleFormatError"
                        :on-success="onMediaSuccess"
                        :on-error="onError"
                        :show-file-list="false">
                    <Button ref="uploadVedioButton" size="small" type="primary">点击上传</Button>
                </Upload>
            </div>
        </div>
    </div>

</template>
<script>

  import AssetsApi from 'assets/js/api/admin/assets'
  // import util from 'assets/js/libs/util'
  // import md5 from 'blueimp-md5'
  // import { quillEditor } from 'vue-quill-editor'
  import { quillEditor } from 'vue-quill-editor'
  export default {
    components: {
      quillEditor
      // quillEditor
    },
    props: {
      value: {
        type: [String,Array],
        default: ''
      },
      editorID:{
        type: String,
        default: 'editor'
      }
    },
    data () {
      let self = this
      return {
        percent:0,
        percentShow:false,
        content:this.value,
        loading: false,
        uploadFormParams: {
          'key': '', //path
          'policy': '', //OssUtilities.signature.policy
          'OSSAccessKeyId': '', //OssUtilities.signature.accessid
          'success_action_status': '200', //让服务端返回200,不然，默认会返回204
          'callback': '',//OssUtilities.signature.accessid
          'signature': '' //OssUtilities.signature.signature
        },
        uploadAction: '',
        toolbar:'formatselect | bold italic strikethrough forecolor backcolor | link | ' +
        'alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat | imgUpload videoUpload',
        options: {
          height: 500,
          language_url: '/js/zh_CN.js' ,
          setup: function (editor) {
            editor.addButton('imgUpload', {
              text: false,
              icon: 'image',
              onclick: function () {
                self.$refs.uploadButton.$el.click()
              }
            });
            editor.addButton('videoUpload', {
              text: false,
              icon: 'media',
              onclick: function () {
                self.$refs.uploadVedioButton.$el.click()
              }
            });
          }
        }
        // innerContent: '<h2 class="ql-align-center"><span class="ql-font-serif">Text content loading..</span></h2>',
      }
    },
    computed: {},
    methods: {
      onChange: function (event) {
        this.updateValue(this.content)
      },
      updateValue (value) {
        this.$emit('input', value);
        // console.log(value);
      },
      handleFormatError (file) {
        this.$Notice.warning({
          title: '格式不正确',
          desc: '该文件格式不正确'
        });
      },
      handleProgress(event){
        this.percent = parseInt(event.percent)
      },
      /**
       *
       */
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      /**
       *
       */
      onError (e) {

        let self = this
        self.loading = false
        self.percentShow =false
        console.log(e)
      },
      /**
       *
       * @param file
       * @returns {Promise<never>}
       */
      async onBeforeUpload (file) {
        let self = this
        self.loading = true
        try {
          let [policyResponse, uploadResponse] = await Promise.all([
            AssetsApi.getAssetsPolicy(),
            AssetsApi.putAssetFile( file.name)
          ])
          if (uploadResponse.data.status === true) {
            self.uploadFormParams.policy = policyResponse.data.policy
            self.uploadFormParams.OSSAccessKeyId = policyResponse.data.accessid
            self.uploadFormParams.callback = policyResponse.data.callback
            self.uploadFormParams.signature = policyResponse.data.signature
            self.uploadFormParams.key = uploadResponse.data.path
            self.uploadAction = policyResponse.data.host
            self.percentShow = true
          } else {
            self.loading = false
            return Promise.reject(new Error(400))
          }
        } catch (e) {
          self.loading = false
          return Promise.reject(new Error(400))
        }
      },
      onMediaSuccess(response){
        let self = this
        self.percentShow =false
        self.percent = 0;
        self.loading = false
        let value = Laravel.imgBaseUrl + '/' + response.object
        self.$refs.editor.editor.insertContent('&nbsp;&nbsp;<p  data-ephox-embed-iri="'+value+'">' +
          '<video width="640"controls="controls">'+
          '<source src="'+value+'" >'+
        '</video></p>&nbsp;&nbsp;')
        this.$emit('uploaded', file)
      },
      onImgSuccess (response, file, fileList) {
        let self = this
        self.loading = false
        self.percentShow =false
        self.percent = 0;
        let value = Laravel.imgBaseUrl + '/' + response.object
        // let addRange = self.$refs.editor.getSelection()
        self.$refs.editor.editor.insertContent('&nbsp;<img src="'+value+'"/>&nbsp;')
        this.$emit('uploaded', file)
      }
    },
    watch:{
      'value': function (newValue) {
        this.content = newValue
      },
    }
  }
</script>
<style>

</style>
